// index.js
// 获取应用实例
import {
  post,
  get,
  put
} from '../../utils/request'
import {
  APIS
} from '../../utils/api';
import {
  systemList
} from '../../utils/system';
import {
  timestampToTime,
  parseData,
  setVoiceSystem,
  setBallSystem
} from '../../utils/util'
const app = getApp();

Page({
  data: {
    isShowTip: false,
    info: {},
    tid: 0,
    orderInfo: {},
    currentMoney: 0,
    runningTime: {},
    orderId: '',
    type: '',
    time: 3,
    statusInfo: {
      1: '进行中',
      2: '待支付',
      3: '已完成'
    },
    isShowKtTip: false,
    dontShow: null
  },
  async onLoad(options) {
    console.log('options', options);
    const {
      order,
      type,
      ball: id,
      dontShow
    } = options;
    this.setData({
      orderId: order,
      type,
      tid: id,
      dontShow
    });
  },
  onShow() {
    let userInfo = wx.getStorageSync('userInfo');
    // 判断用户是否已登录
    if (!userInfo) {
      wx.navigateTo({
        url: '/subPackage/pages/login'
      })
      return;
    }
    this.setData({
      userInfo
    }, () => {
      this.getOrderInfo(this.data.orderId);
    });
  },
  getOrderInfo(orderId) {
    const currentTime = new Date().getTime();
    get(`${APIS.order}/${orderId}`).then(res => {
      const info = res.data;
      let endTime = info.end === '-' || !info.end ? currentTime : info.end;
      console.log(endTime)
      const overTime = endTime - Number(info.start);
      let runningTime = 0;
      if (info.is_usequan) {
        if (info.status === 3) {
          runningTime = parseData(0);
        } else {
          runningTime = parseData(Number(info.end) - Date.now());
        }
      } else {
        runningTime = parseData(overTime)
      }
      this.setData({
        orderInfo: {
          ...info,
          start: timestampToTime(Number(info.start), 1),
        },
        runningTime,
        currentMoney: info.payment
      }, () => {
        if (info.status === 1 && !this.data.dontShow) {
          this.setData({
            isShowKtTip: true
          });
          const that = this;
          const t = setInterval(() => {
            const time = that.data.time - 1;
            that.setData({
              time
            });
            if (that.data.time === 0) {
              that.setData({
                isShowKtTip: false
              });
              clearInterval(t)
            }
          }, 1000);
        }
        console.log(this.data.orderInfo, '================')
      });
    });
  },
  handleShowTip() {
    this.setData({
      isShowTip: true
    });
  },
  handleCloseOrder() {
    if (this.data.userInfo.amount < 0) {
      wx.showToast({
        title: '余额不足，请先充值',
        icon: 'none'
      })
      return;
    } else {
      this.setOrderStatus();
    }
  },
  handleToPay() {
    wx.navigateTo({
      url: '/subPackage/pages/pay'
    })
  },
  async handleOverTask() {
    const url = this.data.type === 'ball' ? APIS.ball : APIS.card;
    // 先修改桌子状态
    put(`${url}/${this.data.tid}`, {
      status: 0,
      action: 'close'
    })
    this.setOrderStatus();
  },
  setOrderStatus() {
    const {
      userInfo
    } = this.data;
    put(`${APIS.order}/${this.data.orderId}`, {
      luid: userInfo.id
    }).then((res) => {
      if (res.data && res.data.user) {
        wx.setStorageSync('userInfo', res.data.user);
      }
      if (res.code !== 0) {
        wx.showToast({
          title: res.message,
          icon: 'none'
        });
        this.getOrderInfo(this.data.orderId)
      } else {
        // 通知硬件
        this.setSystem();
        wx.redirectTo({
          url: `/subPackagePay/pages/complete?orderId=${this.data.orderId}`
        });
        // 退款这个地方要区分下是不是走的退款类型，先放这
        post(`${APIS.refund}`, {
          payment_id: this.data.orderInfo.payment_id,
          uid: this.data.userInfo.id,
          openid: this.data.userInfo.openid
        });
      }
    }).finally(() => {
      this.closePop();
    })
  },
  async setSystem() {
    console.log('----2222', this.data);
    const key = this.data.type === 'ball' ? `b${this.data.tid}` : 'c1';
    const bInfo = systemList.find(x => x.id === key) || {};
    const {
      mcuName,
      mcuid
    } = bInfo;
    await setBallSystem(mcuName, mcuid, 0);
    if (this.data.type === 'ball') {
      await setVoiceSystem(1, `A0${this.data.tid}号桌关台成功，闪电期待您的再次光临，祝您生活愉快`);
    }
  },
  closePop() {
    this.setData({
      isShowTip: false
    });
  },
  onShareAppMessage() {
    return getApp().globalData.shareMessage
  }
})